package com.basic.common.websocket;

import com.basic.common.core.domain.model.LoginUser;
import com.basic.common.utils.TokenUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
 * websocket 拦截器
 *
 * @author zhaoxy_jn@163.com
 */
@Component
public class WsInterceptor implements HandshakeInterceptor{
    @Resource
    TokenUtils tokenService;

    /**
     * 握手前
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes){
        // 获取前端ws请求的 protocols 数据,即token
        List<String> tokens = request.getHeaders().get("Sec-WebSocket-Protocol");
        if(CollectionUtils.isEmpty(tokens)){
            return false;
        }
        // token校验
        String token = tokens.get(0);
        LoginUser loginUser = tokenService.getLoginUser(token);
        // 给WebSocketSession添加参数
        attributes.put("uid",loginUser.getUserId());
        attributes.put("uInfo",loginUser);
        response.getHeaders().put("Sec-WebSocket-Protocol",tokens);
        return true;
    }

    /**
     * 握手后
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param exception
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {}
}
